package com.cro.prison.controller;

import com.alibaba.fastjson.JSON;
import com.cro.prison.entity.pojo.User;
import com.cro.prison.service.UserService;
import com.cro.prison.utils.Code;
import com.cro.prison.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    //植入对象
    @Autowired
    private UserService userService;

    /*返回頁面*/
    @RequestMapping("/getlogin")
    public String getlogin(){
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Result save(@RequestBody User user, HttpSession httpSession) {
        //session中获取信息
        String jsonUser = null;
        User sessionUser = (User)httpSession.getAttribute("user");
        if(sessionUser!=null){
            //已登录
            jsonUser = JSON.toJSONString(sessionUser);
            return new Result(Code.LOGIN_OK,jsonUser);
        }else{
            //未登录
            String pwd = user.getPassword();
            String salt = "lzq";
            String password = DigestUtils.md5DigestAsHex((pwd+salt).getBytes());
            System.out.println(password);


            User loginUser = userService.login(user.getUsername(),password);
            if(loginUser!=null){
                httpSession.setAttribute("user",loginUser);
                System.out.println("成功！！");
                jsonUser = JSON.toJSONString(loginUser);
                return new Result(Code.LOGIN_OK,jsonUser);
            }else{
                System.out.println("失败！！");
                return new Result(Code.LOGIN_ERR,null);
            }
        }
    }

    //登出
    @GetMapping("/logout")
    @ResponseBody
    public Result logout(HttpSession httpSession){

        Object user = httpSession.getAttribute("user");
        if(user!=null){
            httpSession.removeAttribute("user");
            System.out.println("remove success");
            System.out.println(user);
            return new Result(Code.LOGINOUT_OK);
        }else{
            System.out.println("remove failed");
            return new Result(Code.LOGINOUT_OK);
        }
//        return new Result(Code.LOGINOUT_ERR);
    }



}

